package oaSystem.biz.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import oaSystem.Exception.BizException;
import oaSystem.biz.EventBiz;
import oaSystem.entity.Activity;
import oaSystem.entity.ActivityActor;
import oaSystem.entity.Employee;
import oaSystem.entity.Event;
import oaSystem.entity.JsonResult;
import oaSystem.mapper.ActivityActorMapper;
import oaSystem.mapper.ActivityMapper;
@Service
public class EventBizImpl implements EventBiz {
	@Autowired
	private ActivityMapper activityMapper;
	@Autowired
	private ActivityActorMapper activityAcotrMapper;
	
	@Override
	public List<Event> findEventByEmployeeId(Integer employeeId) {
		List<Activity> list = activityMapper.findActivityByCreatorId(employeeId);
		
		List<ActivityActor> actorList = activityAcotrMapper.findActivityActorByEmployeeId(employeeId);
		
		if(actorList!=null&&actorList.size()>0){
			Integer activityId=null;
			for (ActivityActor activityActor : actorList) {
				Activity activity = activityActor.getActivity();
				if(activity.getId()!=activityId){
					activityId=activity.getId();
					list.add(activity);
				}
			}
		}
		
		
		List<Event> eventList = findEventList(list);
		if(eventList!=null&&eventList.size()>0){
			return eventList;
		}
		return null;
	}
	
	
	
	/**
	 * 更新活动
	 * @param event
	 * @param creator
	 * @throws ParseException
	 * @throws BizException
	 */
	@Override
	public void updateActivity(Event event,Employee editor,Boolean isCompleteChange) throws ParseException, BizException{
		String idStr = event.getId();
		
		if(idStr==null||idStr.isEmpty()){
			throw new BizException("更新活动异常，无法获取活动Id");
		}
		Activity activity = activityMapper.fetchActivityById(Integer.parseInt(idStr));
		//检测修改人和创建人是否是同一人
		checkUpdateUser(editor,activity);
		
		if(isCompleteChange){
			activity = formatActivity(event, editor);
		}else{
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Date start = format.parse(event.getStart());
			Date end = format.parse(event.getEnd());
			activity.setStartTime(start);
			activity.setEndTime(end);
		}
		
		activityMapper.updateActivity(activity);
	}

	/**
	 * 删除活动
	 * @param eventId
	 * @param creator
	 * @throws BizException
	 */
	@Transactional(propagation=Propagation.REQUIRED, timeout=60)
	@Override
	public void deleteActivity(Integer eventId,Employee editor) throws BizException {
		//查找活动
		Activity activity = activityMapper.fetchActivityById(eventId);
		//检测修改人和创建人是否是同一人
		checkUpdateUser(editor,activity);
		
		//检查是否有参与者存在，如有先删除参与者
		List<ActivityActor> actorList = activityAcotrMapper.findActivityActorByActivityId(activity.getId());
		if(actorList!=null&&actorList.size()>0){
			for (ActivityActor activityActor : actorList) {
				activityAcotrMapper.deleteActivityActor(activityActor.getId());
			}
		}
		
		//删除活动
		activityMapper.deleteActivity(activity.getId());
	}

	/**
	 * 抽取方法（获取eventList）
	 * @param list
	 * @return
	 */
	private List<Event> findEventList(List<Activity> list) {
		if(list!=null&&list.size()>0){
			Integer activityId=null;
			List<Event> eventList = new ArrayList<Event>();
			Event event=null;
			SimpleDateFormat format=null;
			for (Activity activity : list) {
				if(activityId!=activity.getId()){
					activityId=activity.getId();
					event=new Event();
					Boolean isAllDay = activity.getIsAllDay();
					event.setAllDay(isAllDay.toString());
					event.setColor(activity.getColor().toString());
					event.setId(activity.getId().toString());
					//是否全日
					format=checkIsAllDay(isAllDay);
					Date endTime = activity.getEndTime();
					if(endTime==null){
						event.setEnd("");
					}else{
						event.setEnd(format.format(activity.getEndTime()));
					}
					event.setStart(format.format(activity.getStartTime()));
					event.setTitle(activity.getTitle());
					eventList.add(event);
				}
			}
			return eventList;
		}
		return null;
	}
	@Override
	public JsonResult checkUserIsMatch(Employee editor, Activity activity){
		try {
			checkUpdateUser(editor, activity);
		} catch (BizException e) {
			// TODO Auto-generated catch block
			return new JsonResult(false,e.getMessage());
		}
		return new JsonResult(true, null);
		
	}
	
	/**
	 * 抽取方法（检测修改人和创建人是否是同一人）
	 * @param creator
	 * @param activity
	 * @throws BizException 
	 */
	private void checkUpdateUser(Employee editor, Activity activity) throws BizException {
		if(activity.getCreator().getId()!=editor.getId()){
			throw new BizException("你不是活动创建者，无法修改此活动");
		}
	}

	/**
	 * 抽取方法（格式化Activity）
	 * @param event
	 * @param creator
	 * @return
	 * @throws ParseException
	 */
	private Activity formatActivity(Event event,Employee creator) throws ParseException{
		Activity activity = new Activity();
		activity.setId(Integer.parseInt(event.getId()));
		activity.setColor(event.getColor());
		activity.setCreateTime(new Date());
		activity.setCreator(creator);
		activity.setDescription(event.getDescription());
		
		String allDayStr = event.getAllDay();
		Boolean isAllDay=false;
		if(allDayStr!=null&&!allDayStr.isEmpty()){
			isAllDay=Boolean.parseBoolean(allDayStr);
		}
		//判断是否全日
		SimpleDateFormat format = checkIsAllDay(isAllDay);
		
		Date startDate=null;
		Date endDate=null;

		String end = event.getEnd();
		if(end!=null&&!end.isEmpty()){
			endDate=format.parse(end);
		}
		String start = event.getStart();
		if(start!=null&&!start.isEmpty()){
			startDate=format.parse(start);
		}
		activity.setEndTime(endDate);
		activity.setIsAllDay(isAllDay);
		activity.setLocation(event.getLocation());
		activity.setStartTime(startDate);
		activity.setTitle(event.getTitle());
		return activity;
	}

	/**
	 * 抽取方法（判断是否全日）
	 * @param isAllDay
	 * @return
	 */
	private SimpleDateFormat checkIsAllDay(Boolean isAllDay) {
		SimpleDateFormat format=null;
		if(isAllDay){
			//全天
			format=new SimpleDateFormat("yyyy-MM-dd");
		}else{
			//不是全天
			format=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		}
		return format;
	}
}
